package blog

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/os/glog"
	"time"
)

var articleCache *gcache.Cache

func init() {
	articleCache = gcache.New()
}

type Article struct {
	Id          int
	Title       string    `orm:"size(64)"` // 标题
	Labels      string    `orm:"size(64)"` // 标签
	Classify    int       // 分类
	Introduce   string    `orm:"type(text)"` // 文章简介
	Context     string    `orm:"type(text)"` // 正文
	ReadNum     int       // 阅读数
	Recommend   bool      // 推荐
	Type        int       // 文章类型： 0 正常 1 草稿 2 公告
	Comment     bool      // true 开启评论 false 关闭评论
	KeyWords    string    `orm:"size(128)"`
	Description string    `orm:"size(128)"`
	CreateBy    string    `orm:"size(64)"`
	CreateAt    time.Time `orm:"type(datetime)"` // 创建时间
}

func (m *Article) TableName() string {
	return "blog_articles"
}

func (m *Article) AddRead(address string) {
	key := fmt.Sprintf("%s_%d", address, m.Id)
	if !articleCache.Contains(key) {
		articleCache.Set(key, 1, time.Minute*15)
		_, _ = orm.NewOrm().QueryTable(new(Article)).Filter("id", m.Id).Update(orm.Params{"read_num": orm.ColValue(orm.ColAdd, 1)})
	}
}

func CreateBlogArticle(title, labels, introduce, context string, classify *Classify) error {
	article := Article{
		Title:     title,
		Labels:    labels,
		Classify:  classify.Id,
		Introduce: introduce,
		Context:   context,
		ReadNum:   0,
		CreateAt:  time.Now(),
	}
	_, err := orm.NewOrm().Insert(&article)
	return err
}

func GetArticlesPaginator(limit, page int) (all []Article, total int64, err error) {
	if limit == 0 {
		limit = 10
	}
	if page == 0 {
		page = 1
	}
	total, _ = orm.NewOrm().QueryTable(new(Article)).Count()
	querySet := orm.NewOrm().QueryTable(new(Article)).OrderBy("-id").Offset((page - 1) * limit).Limit(limit)
	_, err = querySet.All(&all)
	return
}

func GetBlogArticlesByClassify(classify *Classify, limit, page int) (all []Article, total int64, err error) {
	querySet := orm.NewOrm().QueryTable(new(Article)).Filter("classify", classify.Id).OrderBy("-create_at")
	total, _ = orm.NewOrm().QueryTable(new(Article)).Filter("classify", classify.Id).Count()
	if limit != 0 && page != 0 {
		querySet = querySet.Offset((page - 1) * limit).Limit(limit)
	}
	_, err = querySet.All(&all)
	return
}

func GetBlogArticles(limit, page int) (all []Article, err error) {
	querySet := orm.NewOrm().QueryTable(new(Article)).OrderBy("-create_at")
	if limit != 0 && page != 0 {
		querySet = querySet.Offset((page - 1) * limit).Limit(limit)
	}
	_, err = querySet.All(&all)
	return
}

func GetBlogArticle(Id int) (blog Article, err error) {
	blog = Article{Id: Id}
	err = orm.NewOrm().Read(&blog)
	return
}

func UpdateBlogArticle(id int, title, context string) error {
	article, err := GetBlogArticle(id)
	if err != nil {
		return err
	}
	article.Title = title
	article.Context = context
	_, err = orm.NewOrm().Update(&article)
	return err
}

func GetHotBlogArticles(limit int64) (articles []Article, err error) {
	querySet := orm.NewOrm().QueryTable(new(Article)).OrderBy("-create_at", "-read_num")
	_, err = querySet.Limit(limit).All(&articles)
	return
}

func DeleteArticle(Id int) error {
	a, err := orm.NewOrm().QueryTable(new(Article)).Filter("id", Id).Delete()
	glog.Debug(a)
	return err
}

func ArticlesCount() int64 {
	t, _ := orm.NewOrm().QueryTable(new(Article)).Count()
	return t
}

func GetAllArticlesCount() {
	var result []orm.Params
	orm.NewOrm().Raw("select classify, count(*) as total from blog_articles group by classify").Values(&result)
}
